import { Context } from 'koa';
import { Client } from '../entity/client';
import { getManager } from 'typeorm';
import { Delivery } from '../entity/delivery';

export default class SummaryController {
  /**
   * 根据用户ID和起始时间生成月结单
   * @param ctx
   */
  public static async generateSummary(ctx: Context) {
    const deliveryRepository = getManager().getRepository(Delivery);

    const clientId: string = ctx.request.body.clientId;
    const start: number = ctx.request.body.start;
    const end: number = ctx.request.body.end;

    // 获取所有符合条件的送货单
    const deliveries = await deliveryRepository
      .createQueryBuilder('delivery')
      .leftJoinAndSelect('delivery.orders', 'order')
      .leftJoinAndSelect('delivery.client', 'client')
      .where('delivery.client.id = :clientId', { clientId })
      .andWhere('delivery.reviewed = :reviewed', { reviewed: true })
      .andWhere('delivery.deliveryDate >= :start', { start })
      .andWhere('delivery.deliveryDate <= :end', { end })
      .orderBy('delivery.deliveryDate', 'DESC')
      .getMany();

    const summaryOrder_list = new Array(0);

    deliveries.map((value) => {
      const orders = value.orders;
      const deliveryNumber = value.deliveryNumber;
      const deliveryId = value.id;
      const deliveryDate = value.deliveryDate;
      orders.map((value) => {
        summaryOrder_list.push(Object.assign({ deliveryNumber, deliveryDate, deliveryId }, value));
      });
    });

    if (deliveries) {
      ctx.status = 200;
      ctx.body = summaryOrder_list;
    } else {
      ctx.status = 500;
    }
  }

  /**
   * 送货单全部付款
   * @param ctx 上下文
   */
  public static async paySummary(ctx: Context) {
    const deliveryRepository = getManager().getRepository(Delivery);

    const deliveryIds: Array<Number> = ctx.request.body.deliveryIds;

    deliveryIds.forEach(async (id) => {
      const delivery = await deliveryRepository
        .createQueryBuilder('delivery')
        .where('delivery.id = :id', { id })
        .getOne();

      if (delivery) {
        delivery.paid = true;
        await deliveryRepository.save(delivery);
      }
    });

    ctx.status = 204;
  }

  /**
   * 送货单全部取消付款
   * @param ctx 上下文
   */
  public static async unPaySummary(ctx: Context) {
    const deliveryRepository = getManager().getRepository(Delivery);

    const deliveryIds: Array<Number> = ctx.request.body.deliveryIds;

    deliveryIds.forEach(async (id) => {
      const delivery = await deliveryRepository
        .createQueryBuilder('delivery')
        .where('delivery.id = :id', { id })
        .getOne();

      if (delivery) {
        delivery.paid = false;
        await deliveryRepository.save(delivery);
      }
    });

    ctx.status = 204;
  }

  /**
   * 统计所有数据
   */
  public static async statistic(ctx: Context) {
    const deliveryRepository = getManager().getRepository(Delivery);
    const deliveries = await deliveryRepository
      .createQueryBuilder('delivery')
      .leftJoinAndSelect('delivery.client', 'client')
      .getMany();

    // 根据客户区分
    const clientMap = new Map<string, Delivery[]>();
    deliveries.forEach((item) => {
      if (clientMap.has(item.client.id)) {
        const arr = clientMap.get(item.client.id) as Delivery[];
        arr.push(item);
      } else {
        clientMap.set(item.client.id, [item]);
      }
    });
    function getMonthString(date: Date) {
      return date.toISOString().split('-')[0] + date.toISOString().split('-')[1];
    }
    const toMonth = getMonthString(new Date());
    let startMonth = new Date('2020-12');
    // 获取所有时间月份
    const monthArr: string[] = [];
    while (1) {
      monthArr.push(getMonthString(startMonth));
      if (toMonth == getMonthString(startMonth)) {
        break;
      }
      startMonth.setMonth(startMonth.getMonth() + 1);
    }
    const ans: { client: Client; arr: { month: string; deliveries: Delivery[] }[] }[] = [];
    // 时间区分
    clientMap.forEach((value) => {
      const monthMap = new Map<string, Delivery[]>();
      monthArr.forEach((item) => {
        monthMap.set(item, []);
      });
      value.forEach((item) => {
        const deliveryArr = monthMap.get(
          item.deliveryDate.toString().substring(0, 6),
        ) as Delivery[];
        deliveryArr.push(item);
      });
      const clientMonthArr: { month: string; deliveries: Delivery[]; summary: number }[] = [];
      monthMap.forEach((item, key) => {
        clientMonthArr.push({
          month: key,
          deliveries: item,
          summary: item.reduce((pre, cur) => pre + cur.totalAmount, 0),
        });
      });
      ans.push({
        client: value[0].client,
        arr: clientMonthArr,
      });
    });
    if (deliveries) {
      ctx.status = 200;
      ctx.body = ans;
    } else {
      ctx.status = 500;
    }
  }
}
